<?php
//消费券及领取操作

namespace App\Repositories;

use App\Models\ConfigModel;
use App\Models\StrategyModel;
use http\Env\Request;


class ConfigRepository extends BaseRepository
{
    public function __construct()
    {

    }

    // 获取单个配置的值
    public function getConfigByKeyword ($keyword, $method = false)
    {
        $user = request()->user();
        $value = ConfigModel::where('keyword', $keyword)
            ->where('admin_id', $user['id'])
            ->value('value');
        if ($method) {
            $value = json_decode($value);
        }
        return $value;
    }

    // 获取多个配置的值
    public function getConfigByKeywords ($keywords)
    {
        $user = request()->user();
        $configs = ConfigModel::whereIn('keyword', $keywords)
            ->where('admin_id', $user['id'])
            ->select('keyword', 'value')
            ->pluck('value', 'keyword');
        return $configs;
    }

    /**
     * 单条更新修改
     * @param $keyword
     * @param $value
     * @return mixed
     */
    public function updateConfigByKeyword ($keyword, $value)
    {
        $user = request()->user();
        $config = ConfigModel::where('keyword', $keyword)
            ->where('admin_id', $user['id'])
            ->first();
        if ($config) {
            $config->value = $value;
        } else {
            $config = new ConfigModel();
            $config->keyword = $keyword;
            $config->value = $value;
            $config->admin_id = $user['id'];
        }
        return $config->save();
    }

    /**
     * 批量更新
     * @param $keywords
     * @param $values
     * @return bool
     */
    public function updateConfigByKeywords ($keyValues)
    {
        $keywords = array_keys($keyValues);
        $user = request()->user();
        $configs = ConfigModel::whereIn('keyword', $keywords)
            ->where('admin_id', $user['id'])
            ->get();
        $result = true;
        foreach ($configs as $config) {
            $config->value = $keyValues[$config->keyword];
            $rst = $config->save();
            if (!$rst) {
                $result = false;
            }
        }
        return $result;
    }
}